package com.googlecode.olabs.common.client.contact.formats.vcard;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.googlecode.olabs.common.client.contact.Contact;
import com.googlecode.olabs.common.client.contact.field.Field;
import com.googlecode.olabs.common.client.contact.formats.Renderer;

public class VCardRenderer implements Renderer {

	public List<String> render(Contact contact) {
		Collection<Field> fields = contact.getFields();
		List<String> result = new ArrayList<String>(fields.size() + 3);
		result.add(VCardFormat.BEGIN_VCARD);
		result.add(VCardFormat.VERSION_3_0);
		for (Field field : fields) {
			result.add(renderLine(field));
		}
		result.add(VCardFormat.END_VCARD);
		return result;
	}

	private String renderLine(Field field) {
		StringBuffer result = new StringBuffer(field.getType());
		for (String subType : field.getSubTypes()) {
			result.append(";");
			result.append(subType);
		}
		result.append(":");
		boolean firstTime = true;
		for (String values : field.getValue()) {
			if (firstTime) {
				firstTime = false;
			} else {
				result.append(";");
			}
			result.append(values);
		}

		return result.toString();
	}
}
